#!/usr/bin/python3
# -*- encoding:utf-8 -*-
# author: king
# create date time: 2024/4/14 下午5:04

"""
日志管理，基于第三方插件 loguru
"""

import os
import sys
import datetime
from loguru import logger

datetime_obj = datetime.datetime.now()


class CustomLogger(object):
    """
    自定义 loguru 日志
    """

    def __init__(self, **kwargs):
        self.log_name = kwargs.get("log_name") or __name__
        self.log_path = kwargs.get("log_path") or "logs"
        self.log_level = kwargs.get("log_level") or "DEBUG"
        self.log_format = (
            kwargs.get("log_format")
            or "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
            "<level>{message}</level>"
        )
        self.rotation = kwargs.get("rotation") or "10 MB"
        self.retention = kwargs.get("retention") or "7 days"
        self.log_file_encoding = kwargs.get("encoding") or "utf-8"

        self.new_log_path = os.path.join(self.log_path, datetime_obj.strftime("%Y%m%d"))

        if not os.path.exists(self.new_log_path):
            os.makedirs(self.new_log_path, exist_ok=True)

        self.logger = logger
        self.logger.remove()

        self.console_output()
        self.info_log_file_output()
        self.error_log_file_output()

    def console_output(self):
        """
        控制台输出
        :author: king
        :create date time: 2024/4/14 下午5:16
        """
        self.logger.add(
            sys.stdout,
            level="INFO",
            format=self.log_format,
        )

    def info_log_file_output(self):
        """
        :return:
        :author: king
        :create date time: 2024/4/14 下午5:16
        """
        info_filepath = os.path.join(self.new_log_path, f"info_{self.log_name}_{datetime_obj.strftime('%Y%m%d')}.log")
        self.logger.add(
            info_filepath,
            level="DEBUG",
            format=self.log_format,
            filter=lambda records: records["level"].no <= 30,
            enqueue=True,
            rotation=self.rotation,
            retention=self.retention,
            encoding=self.log_file_encoding,
        )

    def error_log_file_output(self):
        """
        :return:
        :author: king
        :create date time: 2024/4/14 下午5:22
        """
        error_filepath = os.path.join(self.new_log_path, f"error_{self.log_name}_{datetime_obj.strftime('%Y%m%d')}.log")
        self.logger.add(
            error_filepath,
            level="DEBUG",
            format=self.log_format,
            filter=lambda records: records["level"].no > 30,
            enqueue=True,
            rotation=self.rotation,
            retention=self.retention,
            encoding=self.log_file_encoding,
        )


def main():
    """程序入口"""
    cl = CustomLogger()
    cl.logger.debug("debug")
    cl.logger.info("info")
    cl.logger.error("error")
    cl.logger.warning("warning")
    cl.logger.critical("critical")


if __name__ == "__main__":
    main()
